package com.business.dashboard.controller;

import com.business.dashboard.entity.AdminUser;
import com.business.dashboard.entity.User;
import com.business.dashboard.entity.NewsArticle;
import com.business.dashboard.entity.BusinessPlan;
import com.business.dashboard.service.AdminUserService;
import com.business.dashboard.service.UserService;
import com.business.dashboard.service.NewsArticleService;
import com.business.dashboard.service.BusinessPlanService;
// import com.business.dashboard.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理后台页面控制器 (前后端不分离)
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminPageController {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private NewsArticleService newsArticleService;

    @Autowired
    private BusinessPlanService businessPlanService;

    // @Autowired
    // private JwtUtil jwtUtil;

    /**
     * 管理后台登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 管理后台首页 - 仪表板
     */
    @GetMapping({"", "/", "/dashboard"})
    public String dashboard(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        try {
            // 获取统计数据
            Map<String, Object> stats = getDashboardStats();
            model.addAttribute("stats", stats);

            // 获取最近用户
            List<User> recentUsers = getRecentUsers(10);
            model.addAttribute("recentUsers", recentUsers);

            // 页面标题和导航
            model.addAttribute("pageTitle", "仪表板");
            model.addAttribute("activeNav", "dashboard");

            return "admin/dashboard";
        } catch (Exception e) {
            log.error("加载仪表板数据失败", e);
            model.addAttribute("error", "加载数据失败");
            return "admin/dashboard";
        }
    }

    /**
     * 用户管理页面
     */
    @GetMapping("/users")
    public String usersPage(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        try {
            // 获取用户列表
            List<User> users = userService.getUserList(1, 50, null, null, null);
            model.addAttribute("users", users);
            
            // 添加统计信息
            long totalUsers = userService.getUserCount();
            model.addAttribute("totalUsers", totalUsers);

            // 页面标题和导航
            model.addAttribute("pageTitle", "用户管理");
            model.addAttribute("activeNav", "users");
            return "admin/users";
        } catch (Exception e) {
            log.error("加载用户列表失败", e);
            model.addAttribute("error", "加载用户列表失败");
            model.addAttribute("users", new java.util.ArrayList<>());
            model.addAttribute("template", "admin/users :: content");
            return "admin/layout";
        }
    }

    /**
     * 管理员管理页面
     */
    @GetMapping("/admins")
    public String adminsPage(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        try {
            // 获取管理员列表
            List<AdminUser> admins = adminUserService.getAllUsers();
            // 清除密码信息
            admins.forEach(admin -> admin.setPassword(null));
            model.addAttribute("admins", admins);

            // 页面标题和导航
            model.addAttribute("pageTitle", "管理员管理");
            model.addAttribute("activeNav", "admins");
            return "admin/admins";
        } catch (Exception e) {
            log.error("加载管理员列表失败", e);
            model.addAttribute("error", "加载管理员列表失败");
            model.addAttribute("admins", new java.util.ArrayList<>());
            model.addAttribute("template", "admin/admins :: content");
            return "admin/layout";
        }
    }

    /**
     * 内容管理页面
     */
    @GetMapping("/news")
    public String newsPage(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        try {
            // 获取文章列表
            List<NewsArticle> articles = newsArticleService.getArticleList(1, 50, null, null, null);
            model.addAttribute("articles", articles);
            
            // 获取统计数据
            long totalArticles = newsArticleService.getArticleCount();
            int publishedCount = newsArticleService.getArticleCountByStatus("published");
            int draftCount = newsArticleService.getArticleCountByStatus("draft");
            int archivedCount = newsArticleService.getArticleCountByStatus("archived");
            
            model.addAttribute("totalArticles", totalArticles);
            model.addAttribute("publishedCount", publishedCount);
            model.addAttribute("draftCount", draftCount);
            model.addAttribute("archivedCount", archivedCount);
            
            model.addAttribute("pageTitle", "内容管理");
            model.addAttribute("activeNav", "news");

            return "admin/news";
        } catch (Exception e) {
            log.error("加载文章列表失败", e);
            model.addAttribute("error", "加载文章列表失败");
            model.addAttribute("articles", new java.util.ArrayList<>());
            model.addAttribute("totalArticles", 0);
            model.addAttribute("publishedCount", 0);
            model.addAttribute("draftCount", 0);
            model.addAttribute("archivedCount", 0);
            model.addAttribute("pageTitle", "内容管理");
            model.addAttribute("activeNav", "news");
            return "admin/news";
        }
    }

    /**
     * 商业计划书管理页面
     */
    @GetMapping("/business-plans")
    public String businessPlansPage(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        try {
            // 获取商业计划书列表
            List<BusinessPlan> plans = businessPlanService.getPlanList(1, 50, null, null, null, null);
            model.addAttribute("plans", plans);
            
            // 获取统计数据
            long totalPlans = businessPlanService.getPlanCount();
            int draftCount = businessPlanService.getPlanCountByStatus("draft");
            int completedCount = businessPlanService.getPlanCountByStatus("completed");
            int publishedCount = businessPlanService.getPlanCountByStatus("published");
            
            model.addAttribute("totalPlans", totalPlans);
            model.addAttribute("draftCount", draftCount);
            model.addAttribute("completedCount", completedCount);
            model.addAttribute("publishedCount", publishedCount);
            
            model.addAttribute("pageTitle", "商业计划书管理");
            model.addAttribute("activeNav", "businessPlans");

            return "admin/business-plans";
        } catch (Exception e) {
            log.error("加载商业计划书列表失败", e);
            model.addAttribute("error", "加载商业计划书列表失败");
            model.addAttribute("plans", new java.util.ArrayList<>());
            model.addAttribute("totalPlans", 0);
            model.addAttribute("draftCount", 0);
            model.addAttribute("completedCount", 0);
            model.addAttribute("publishedCount", 0);
            model.addAttribute("pageTitle", "商业计划书管理");
            model.addAttribute("activeNav", "businessPlans");
            return "admin/business-plans";
        }
    }

    /**
     * 系统设置页面
     */
    @GetMapping("/settings")
    public String settingsPage(Model model, HttpServletRequest request) {
        // 暂时跳过认证检查
        // if (!validateAdminAuth(request)) {
        //     return "redirect:/admin/login";
        // }

        // TODO: 实现系统设置功能
        model.addAttribute("pageTitle", "系统设置");
        model.addAttribute("activeNav", "settings");
        model.addAttribute("message", "系统设置功能开发中...");
        return "admin/settings";
    }

    /**
     * 验证管理员认证 (简化版，使用session)
     */
    private boolean validateAdminAuth(HttpServletRequest request) {
        // 简化验证：检查session中是否有admin标识
        Object adminId = request.getSession().getAttribute("adminId");
        return adminId != null;
    }


    /**
     * 获取仪表板统计数据
     */
    private Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 用户统计
            long totalUsers = userService.getUserCount();
            stats.put("totalUsers", totalUsers);
            stats.put("activeUsers", getActiveUserCount()); // 活跃用户数（状态为1）
            stats.put("todayNewUsers", getTodayNewUsers()); // 今日新增用户
            stats.put("monthNewUsers", getMonthNewUsers()); // 本月新增用户
            
            // 内容统计
            long totalNews = newsArticleService.getArticleCount();
            long totalPlans = businessPlanService.getPlanCount();
            stats.put("totalNews", totalNews);
            stats.put("totalPlans", totalPlans);
            
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            stats.put("totalUsers", 0);
            stats.put("activeUsers", 0);
            stats.put("todayNewUsers", 0);
            stats.put("monthNewUsers", 0);
            stats.put("totalNews", 0);
            stats.put("totalPlans", 0);
        }
        
        return stats;
    }

    /**
     * 获取最近用户
     */
    private List<User> getRecentUsers(int limit) {
        try {
            return userService.getUserList(1, limit, null, null, null);
        } catch (Exception e) {
            log.error("获取最近用户失败", e);
            return new java.util.ArrayList<>();
        }
    }

    /**
     * 获取活跃用户数量
     */
    private long getActiveUserCount() {
        try {
            // 这里简化实现，可以后续优化为更复杂的活跃度判断
            List<User> allUsers = userService.getUserList(1, Integer.MAX_VALUE, null, null, null);
            return allUsers.stream().filter(user -> user.getStatus() == 1).count();
        } catch (Exception e) {
            log.error("获取活跃用户数失败", e);
            return 0;
        }
    }

    /**
     * 获取今日新增用户数
     */
    private long getTodayNewUsers() {
        try {
            // 这里简化实现，实际应该用SQL查询今天注册的用户
            // TODO: 优化为SQL查询
            return 0; // 暂时返回0
        } catch (Exception e) {
            log.error("获取今日新增用户数失败", e);
            return 0;
        }
    }

    /**
     * 获取本月新增用户数
     */
    private long getMonthNewUsers() {
        try {
            // 这里简化实现，实际应该用SQL查询本月注册的用户
            // TODO: 优化为SQL查询
            return 0; // 暂时返回0
        } catch (Exception e) {
            log.error("获取本月新增用户数失败", e);
            return 0;
        }
    }

}